package flinkSql.window.group;

import bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Slide;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.junit.Test;

import static org.apache.flink.table.api.Expressions.*;

//TODO 处理时间计数窗口
public class Flink_ProcessTime_GroupWindow_Slide_Count {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] split = value.split(",");
                    return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                });

        Table table = tableEnvironment.fromDataStream(input, $("id"), $("ts"), $("temp"), $("pt").proctime());

        //table API
        Table select1 = table.window(Slide.over(rowInterval(5L)).every(rowInterval(2L)).on($("pt")).as("sw"))
                .groupBy($("sw"), $("id"))
                .select($("id"), $("temp").sum());

//        tableEnvironment.createTemporaryView("sqlTable",table);
//        Table select1 = tableEnvironment.sqlQuery("select id,sum(temp) from sqlTable group by id,hop(pt,interval '5' rows,interval '10' rows)");
        tableEnvironment.toAppendStream(select1,Row.class).print("sql");

        env.execute();
    }
}
